﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Text;
using Emgu.CV;
using Emgu.Util;
using Emgu.CV.Structure;
using Emgu.CV.CvEnum;

namespace FaceFromCamera
{
    class RecognitionEngineModel
    {
        #region SingleTon
        static RecognitionEngineModel instance;
        public static RecognitionEngineModel Instance
        {
            get
            {
                if (instance == null)
                    instance = new RecognitionEngineModel();
                return instance;
            }
        }

        #endregion
        #region Declarations
        public Bitmap faceOnly{set; get;}
        #endregion

        public Image Frame(Capture cap, HaarCascade haar)
        {
            try
            {
                using (Image<Bgr, byte> nextFrame = cap.QueryFrame())
                {
                    if (nextFrame != null)
                    {
                        Image<Gray, byte> grayframe = nextFrame.Convert<Gray, byte>();
                        var faces =
                                grayframe.DetectHaarCascade(
                                        haar, 1.4, 4,
                                        HAAR_DETECTION_TYPE.DO_CANNY_PRUNING,
                                        new Size(nextFrame.Width / 8, nextFrame.Height / 8)
                                        )[0];
                        if (faces.Length > 0)
                        {
                            nextFrame.Draw(faces[0].rect, new Bgr(Color.Red), 3);
                            faceOnly = PictureOperations.Copy(nextFrame.ToBitmap(), faces[0].rect);

                        }
                    }
                    return nextFrame.ToBitmap();
                }
            }
            catch (Exception e) {
                return null;
            }
            
        }
        public string Recognize(Image<Gray, byte>[] faces, string[] id)
        {
            try
            {
                MCvTermCriteria term = new MCvTermCriteria(1000, 0.00001);
                EigenObjectRecognizer p = new EigenObjectRecognizer(faces, id, ref term);
                Image<Gray, byte> twarz = new Image<Gray, byte>(PictureOperations.ResizeImage(new Bitmap(faceOnly), 64, 64));
                if (twarz.Width == 64 && twarz.Height == 64)
                {
                    twarz._EqualizeHist();
                    return p.Recognize(twarz);
                }
                else { return "0"; }
            }
            catch (Exception e) {
                return "0";
            }
        }

    }
}
